<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/7/23
 * Time: 0:13
 */
namespace App\Http\Controllers\Home\User;

use App\Helper\Helpers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    public function register()
    {
        if(!empty($_POST))
        {
            if(empty($_POST['name']))
            {
                return json_encode(['code'=>-1,'msg'=>'请输入姓名']);
            }else if(empty($_POST['name']))
            {
                return json_encode(['code'=>-1,'msg'=>'请选择您的性别']);
            }else if(empty($_POST['birthday']))
            {
                return json_encode(['code'=>-1,'msg'=>'请选择您的出生年月']);
            }else if(empty($_POST['addressId']))
            {
                return json_encode(['code'=>-1,'msg'=>'请选择地址']);
            }else if(empty($_POST['phone']) || mb_strlen($_POST['phone']) != 11 || !preg_match("/^[1][0-9][0-9]{9}$/",$_POST['phone']))
            {
                return json_encode(['code'=>-1,'msg'=>'请输入正确的手机号码']);
            }else if (empty($_POST['pass']))
            {
                return json_encode(['code'=>-1,'msg'=>'请设置您的密码']);
            }else if($_POST['pass'] != $_POST['pwdtwo'])
            {
                return json_encode(['code'=>-1,'msg'=>'密码不一致']);
            }else if(empty($_POST['email']))
            {
                return json_encode(['code'=>-1,'msg'=>'请输入邮箱']);
            }else if(!preg_match("/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/",$_POST['email']))
            {
                return json_encode(['code'=>-1,'msg'=>'请输入正确的邮箱']);
            }else{

                //手机号不能重复
                $phone = DB::table('user')->where('phone',$_POST['phone'])->where('status',1)->first();
                if(!empty($phone))
                {
                    return json_encode(['code'=>-1,'msg'=>'手机号码重复']);
                    die;
                }
                if(!empty($_POST['pid'])){
                    $_POST['pid'] = substr($_POST['pid'],3,(strlen($_POST['pid']-3)));
                    //验证邀请人是否存在
                    $hasJoin = DB::table('user')->where('id',$_POST['pid'])->where('point','>',0)->first();
                    if(empty($hasJoin))
                    {
                        return json_encode(['code'=>-1,'msg'=>'您填写的邀请码不存在或代理人代理点不足']);
                        die;
                    }
                }

                //手机验证码检测
                if(empty($_POST['yzcode']))
                {
                    return json_encode(['code'=>-1,'msg'=>'请输入正确的手机验证码']);
                    die;
                }else{
                    //数据库检测是否存在
                    $time = time();
                    $hasSms = DB::table('sms')
                        ->select('id','create_time')
                        ->where('status',1)
                        ->where('phone',$_POST['phone'])
                        ->where('code',$_POST['yzcode'])
                        ->first();
                    if(!empty($hasSms->id))
                    {
                        $timeJ = $time-$hasSms->create_time;
                        if($timeJ > 600)
                        {
                            return json_encode(['code'=>-1,'msg'=>'请输入正确的手机验证码']);
                            die;
                        }else{
                            DB::table('sms')->where('id',$hasSms->id)->update(['status'=>2]);
                        }
                    }else{
                        return json_encode(['code'=>-1,'msg'=>'请输入正确的手机验证码']);
                        die;
                    }
                }

//                $name_=$_POST["name"];
//                $sex_=$_POST["sex"];
//                $birth_=$_POST["birthday"];//EX:2017-2-2
//                $email_=$_POST["email"];
//                $url = "https://robinlintec.com.tw/codeapigo/apiadd.asp";
//                $data = "act=0&fid=256888&fps=987452&name=". $name_."&sex=". $sex_."&birth=". $birth_."&email=". $email_ ;
//                $curlInfo = $this->http_post_data($url, $data);
//                if(!empty($curlInfo))
//                {
//                    $curlInfo = explode('-',$curlInfo);
//                    if($curlInfo[1] == 0)
//                    {
//                        $_POST['rob_name'] = $curlInfo[2];
//                        $_POST['rob_pass'] = $curlInfo[3];
//                        $_POST['rob_uid'] = $curlInfo[4];
//                        $_POST['rob_errorid'] = $curlInfo[1];
                        unset($_POST['_token']);
                        unset($_POST['pwdtwo']);
                        unset($_POST['yzcode']);
                        $_POST['pass'] = password_hash($_POST['pass'], PASSWORD_DEFAULT);
                        $_POST['create_time'] = time();
                        $_POST['status'] = 1;
                        $_POST['user_role'] = 1;
                        $addressId = !empty($_POST['addressId']) ? explode(',',$_POST['addressId']) : '';
                        if(!empty($addressId[0])) $_POST['province_id'] = $addressId[0];
                        if(!empty($addressId[1])) $_POST['city_id'] = $addressId[1];
                        if(!empty($addressId[2])) $_POST['area_id'] = $addressId[2];
                        unset($_POST['addressId']);
                        $res = DB::table('user')->insertGetId($_POST);
                        $isSuccess = $res ? 'success' : 'error';
                        \Helpers::insertUserActionLog('UserReg','add',$res,$isSuccess,$_POST);
                        if($res){
                            return json_encode(['code'=>1,'msg'=>'注册成功!']);
                        }else{
                            return json_encode(['code'=>-1,'msg'=>'注册失败!']);
                        }
//                    }else if($curlInfo[1] == 1)
//                    {
//                        return json_encode(['code'=>-1,'msg'=>'开通指纹账号Ip错误!']);
//                    }else if($curlInfo[1] == 2)
//                    {
//                        return json_encode(['code'=>-1,'msg'=>'开通指纹账号账密错误!']);
//                    }else if($curlInfo[1] == 3)
//                    {
//                        return json_encode(['code'=>-1,'msg'=>'开通指纹账号脚本错误!']);
//                    }else if($curlInfo[1] == 11)
//                    {
//                        return json_encode(['code'=>-1,'msg'=>'email重复!']);
//                    }
//                }else{
//                    return json_encode(['code'=>-1,'msg'=>'开通指纹账号失败!']);
//                }
            }
            die;
        }
        //获取省的数据
        $provs_data = DB::table('area')
                        ->select('id as value','name as text')
                        ->where('level',1)
                        ->where('status',1)
                        ->get();
        $data['provs_data'] = $provs_data;
        $data['citys_data'] = [];
        $data['dists_data'] = [];
        if(!empty($provs_data))
        {
            foreach ($provs_data as $pk=>$pv)
            {
                $citys_data = DB::table('area')
                    ->select('id as value','name as text')
                    ->where('pid',$pv->value)
                    ->where('level',2)
                    ->where('status',1)
                    ->get();
                $data['citys_data'][$pv->value] = $citys_data;
            }
        }

        if(!empty($data['citys_data']))
        {
            foreach ($data['citys_data'] as $pk1=>$pv1)
            {
                foreach($pv1 as $pk2 => $pv2){
                    $dists_data = DB::table('area')
                        ->select('id as value','name as text')
                        ->where('pid',$pv2->value)
                        ->where('level',3)
                        ->where('status',1)
                        ->get();
                    $data['dists_data'][$pv2->value] = $dists_data;
                }
            }
        }
        return view('Home.User.index')->withData($data);
    }

    private  function http_post_data($url, $data_string) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        ob_start();

        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $return_content;
    }

    public function login()
    {
        $data = [];
        if(!empty($_POST))
        {
            if(empty($_POST['telephone']) || mb_strlen($_POST['telephone']) != 11 || !preg_match("/^[1][0-9][0-9]{9}$/",$_POST['telephone']))
            {
                return json_encode(['code'=>-1,'msg'=>'请输入正确的手机号码!']);
            }else if(empty($_POST['password'])){
                return json_encode(['code'=>-1,'msg'=>'请输入密码!']);
            }else{
                $phone = DB::table('user')->where('phone',$_POST['telephone'])->where('status',1)->first();
                if(empty($phone))
                {
                    $data['error'] = '<font color="red">账号不存在!</font>';
                }else if(!password_verify ( $_POST['password'], $phone->pass)){
                    $data['error'] = '<font color="red">密码错误!</font>';
                }else{
                    session(['User' => json_encode($phone,true)]);
                    return header('Location:'.__BASE__.'/home/index');
                    die;
                }
            }
        }
        return view('Home.User.login')->withData($data);
    }

    public function logout()
    {
        session()->forget('User');
        $user = session('User');
        if(empty($user))
        {
            return json_encode(['code'=>1,'msg'=>"登出成功"]);
        }else{
            return json_encode(['code'=>-1,'msg'=>"登出失败"]);
        }
    }

    public function forgetpass()
    {
        $data = [];
        return view('Home.User.forgetpass')->withData($data);
    }

    /**
     * 验证码
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @param   <null>
     * @return  <img>  [验证码]
     */
    public function captcha()
    {
        //实例化验证码类
        $captcha = new \CaptchaClass();
        //生成验证码
        $captcha->doimg();
        //存入session
        session(['Z_HOME_Captcha' => $captcha->getCode()]);
    }

    //手机验证码发送
    public function sendsms()
    {
        $smsData = [];
        $phone = $_POST['phone'];
        if(empty($phone) || !preg_match("/^[1][0-9][0-9]{9}$/",$phone))
        {
            return json_encode(['code'=>-1,'msg'=>"请输入正确的手机号码"]);
        }else{
            //数据库检测当前手机号今日请求短信发送数量
            $start_time = strtotime(date('Y-m-d 00:00'));
            $hasNum = DB::table('sms')
                        ->where('phone',$phone)
                        ->where('create_time','>',$start_time)
                        ->count();
            if($hasNum > 5)
            {
                return json_encode(['code'=>-1,'msg'=>"您的请求过于频繁,请明日再发送请求!"]);
            }else{
                //检测是否需要图片验证码
                if(!empty($_POST['type']) && $_POST['type'] == 2)
                {
                    if(empty($_POST['imgcode']))
                    {
                        return json_encode(['code'=>-1,'msg'=>"请输入图片验证码"]);
                    }else{
                        if(session('Z_HOME_Captcha') != $_POST['imgcode'])
                        {
                            return json_encode(['code'=>-1,'msg'=>"图片验证码错误"]);
                        }
                    }
                }
                $smsData['phone'] = $phone;
                $smsData['code'] = rand(00000,99999);
                $smsData['create_time'] = time();
                $smsData['status'] = 1;
                $statusStr = array(
                    "0" => "短信发送成功",
                    "-1" => "参数不全",
                    "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
                    "30" => "密码错误",
                    "40" => "账号不存在",
                    "41" => "余额不足",
                    "42" => "帐户已过期",
                    "43" => "IP地址限制",
                    "50" => "内容含有敏感词"
                );
                $smsapi = "http://api.smsbao.com/";
                $user = "illuminate"; //短信平台帐号
                $pass = md5("yqtf01949194"); //短信平台密码
                $content="【云启天赋】尊敬的客户，您的验证码为".$smsData['code']."，在10分钟内有效。 ";//要发送的短信内容
                $phone = $smsData['phone'];//要发送短信的手机号码
                $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
                $result =file_get_contents($sendurl) ;
                if($result == 0)
                {
                    DB::table('sms')->insert($smsData);
                    return json_encode(['code'=>1,'msg'=>$statusStr[$result]]);
                }else{
                    return json_encode(['code'=>-1,'msg'=>$statusStr[$result]]);
                }
            }
        }
    }

    public function replaypass()
    {
        $phone = $_POST['phone'];
        if(empty($phone) || !preg_match("/^[1][0-9][0-9]{9}$/",$phone))
        {
            return json_encode(['code'=>-1,'msg'=>"请输入正确的手机号码"]);
        }else if(empty($_POST['imgcode'])){
            return json_encode(['code'=>-1,'msg'=>"请输入图片验证码"]);
        }else if(session('Z_HOME_Captcha') != $_POST['imgcode']){
            return json_encode(['code'=>-1,'msg'=>"图片验证码错误"]);
        }else if(empty($_POST['yzcode'])){
            return json_encode(['code'=>-1,'msg'=>"请输入手机验证码"]);
        }else
        {

            if(empty($_POST['password']))
            {
                return json_encode(['code'=>-1,'msg'=>'请输入您的新密码']);
                die;
            }else if(empty($_POST['newcode'])){
                return json_encode(['code'=>-1,'msg'=>'请再次输入您的新密码']);
                die;
            }else if($_POST['password'] != $_POST['newcode'])
            {
                return json_encode(['code'=>-1,'msg'=>'密码不一致']);
                die;
            }else{
                //检测新密码不能跟老密码相同
                $getUserInfo = DB::table('user')
                                ->select('id','pass')
                                ->where('status',1)
                                ->where('phone',$phone)
                                ->first();
                if(!empty($getUserInfo))
                {
                    if(password_verify($_POST['password'],$getUserInfo->pass))
                    {
                        return json_encode(['code'=>-1,'msg'=>'新密码不能与旧密码一样']);
                        die;
                    }else{

                        //数据库检测是否存在
                        $time = time();
                        $hasSms = DB::table('sms')
                            ->select('id','create_time')
                            ->where('status',1)
                            ->where('phone',$_POST['phone'])
                            ->where('code',$_POST['yzcode'])
                            ->first();
                        if(!empty($hasSms->id))
                        {
                            $timeJ = $time-$hasSms->create_time;
                            if($timeJ > 600)
                            {
                                return json_encode(['code'=>-1,'msg'=>'请输入正确的手机验证码']);
                                die;
                            }else{
                                DB::table('sms')->where('id',$hasSms->id)->update(['status'=>2]);
                            }
                        }else{
                            return json_encode(['code'=>-1,'msg'=>'请输入正确的手机验证码']);
                            die;
                        }

                        $res = DB::table('user')
                                    ->where('id',$getUserInfo->id)
                                    ->update(['pass'=>password_hash($_POST['password'],PASSWORD_DEFAULT)]);
                        if($res)
                        {
                            return json_encode(['code'=>1,'msg'=>'修改密码成功']);
                            die;
                        }else{
                            return json_encode(['code'=>-1,'msg'=>'修改密码失败']);
                            die;
                        }
                    }
                }else{
                    return json_encode(['code'=>-1,'msg'=>'该用户不存在']);
                    die;
                }
            }

        }
    }

    public function notify()
    {
        require_once base_path()."/vendor/wxpay/lib/WxPay.Api.php";
        require_once base_path().'/vendor/wxpay/lib/WxPay.Notify.php';
        require_once base_path()."/vendor/wxpay/example/WxPay.Config.php";
        require_once base_path().'/vendor/wxpay/example/log.php';
        //初始化日志
        $logHandler= new \CLogFileHandler(base_path().'/vendor/wxpay/logs/'.date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);
        $getInfo = json_encode($_REQUEST);
        $post = $_REQUEST;
        if ($post == null) {
            \Log::DEBUG("REQUEST获取不到数据");
            $post = file_get_contents("php://input");
        }

        if ($post == null) {
            $post = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
            \Log::DEBUG("file_get_contents获取不到数据");
        }

        if (empty($post) || $post == null || $post == '') {
            //阻止微信接口反复回调接口  文档地址 https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=9_7&index=7，下面这句非常重要!!!
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            echo $str;
            \Log::DEBUG("Notify 非法回调");
            exit('Notify 非法回调');
        }

        /*****************微信回调返回数据样例*******************
        $post = '<xml>
        <return_code><![CDATA[SUCCESS]]></return_code>
        <return_msg><![CDATA[OK]]></return_msg>
        <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
        <mch_id><![CDATA[10000100]]></mch_id>
        <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>
        <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>
        <result_code><![CDATA[SUCCESS]]></result_code>
        <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>
        <trade_type><![CDATA[APP]]></trade_type>
        </xml>';
         *************************微信回调返回*****************/

        libxml_disable_entity_loader(true); //禁止引用外部xml实体

        $xml = simplexml_load_string($post, 'SimpleXMLElement', LIBXML_NOCDATA);//XML转数组

        $post_data = (array)$xml;
        $post_data1 = json_encode($post_data);
        \Log::DEBUG($post_data1);
        $out_trade_no = isset($post_data['out_trade_no']) && !empty($post_data['out_trade_no']) ? $post_data['out_trade_no'] : 0;
        //查询数据库订单
        $orderInfo = DB::table('order')
                        ->where('order_no',$out_trade_no)
                        ->where('status',1)
                        ->first();
        if(!empty($orderInfo->id))
        {
            $key = '8934e7d15453e97507ef794cf7b0519d';
            //接收到的签名
            $post_sign = $post_data['sign'];
            unset($post_data['sign']);

            //重新生成签名
            $newSign = $this->MakeSign($post_data,$key);
            if($post_sign == $newSign){

                $updateData = array();
                $updateData['pay_time'] = time(); //支付时间
                $updateData['status'] = 2; //订单状态
                //更新order数据库
                $updateData['transaction_id'] = $post_data['transaction_id'];
                $res = DB::table('order')
                        ->where('order_no',$out_trade_no)
                        ->where('status',1)
                        ->update($updateData);
                if(!empty($orderInfo->pid))
                {
                    if($orderInfo->type == 1)
                    {
                        //给用户开通指纹账户
                        $getUserInfo = DB::table('user')->where('id',$orderInfo->uid)->first();
                        $name_=$getUserInfo->name;
                        $sex_=$getUserInfo->sex;
                        $birth_=$getUserInfo->birthday;//EX:2017-2-2
                        $email_=$getUserInfo->email;
                        $url = "https://robinlintec.com.tw/codeapigo/apiadd.asp";
                        $data = "act=0&fid=256888&fps=987452&name=". $name_."&sex=". $sex_."&birth=". $birth_."&email=". $email_ ;
                        $curlInfo = $this->http_post_data($url, $data);
                        \Log::DEBUG($curlInfo);
                        if(!empty($curlInfo))
                        {
                            $curlInfo = explode('-',$curlInfo);
                            if($curlInfo[1] == 0) {
                                $insertD['rob_name'] = $curlInfo[2];
                                $insertD['rob_pass'] = $curlInfo[3];
                                $insertD['rob_uid'] = $curlInfo[4];
                                $insertD['rob_errorid'] = $curlInfo[1];
                                $res = DB::table('user')->where('id',$orderInfo->uid)->update($insertD);
                                $isSuccess = $res ? 'success' : 'error';
                                \Helpers::insertUserActionLog('UserZwReg','add',$res,$isSuccess,$insertD);
                            }else{
                                \Helpers::insertUserActionLog('UserZwReg','add',$res,'error',$curlInfo);
                            }
                        }else{
                            \Helpers::insertUserActionLog('UserZwReg','fail',0,'error',$curlInfo);
                        }
                    }
                    $res1 = DB::table('user')->where('id',$orderInfo->pid)->where('point','>',0)->decrement('point', 1);
                    if($res1)
                    {
                        DB::table('user')->where('id',$orderInfo->pid)->increment('money',$orderInfo->paymoney);
                    }
                }
            }

        }
        //阻止微信接口反复回调接口  文档地址 https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=9_7&index=7，下面这句非常重要!!!
        $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        echo $str;
    }

    private function MakeSign($params,$key){
        //签名步骤一：按字典序排序数组参数
        ksort($params);
        $string = $this->ToUrlParams($params);  //参数进行拼接key=value&k=v
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=".$key;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    private function ToUrlParams( $params ){
        $string = '';
        if( !empty($params) ){
            $array = array();
            foreach( $params as $key => $value ){
                $array[] = $key.'='.$value;
            }
            $string = implode("&",$array);
        }
        return $string;
    }

}